﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MongoDBManager
{
    /// <summary>
    /// Log日志类
    /// </summary>
    public static class Log
    {

        /// <summary>
        /// log路径
        /// </summary>
        private static string logpath;

        /// <summary>
        /// task任务
        /// </summary>
        private static Task _tasklog;

        /// <summary>
        /// 日志队列
        /// </summary>
        private static Queue<string> _queuelog = new Queue<string>();

        static Log()
        {
            GetLogPath();
            _tasklog = Task.Run(() =>
            {
                while (true)
                {
                    Thread.Sleep(1000);
                    if (_queuelog.Count > 0)
                    {
                        string msg = _queuelog.Dequeue();
                        File.AppendAllText(logpath, msg);
                        IsDeleteFile();
                    }
                }
            });
        }
        /// <summary>
        /// 写入信息日志
        /// </summary>
        public static void Info(string info)
        {
            WriteMessage("info", info);
        }

        /// <summary>
        /// 写入信息日志
        /// </summary>
        public static void Error(string error)
        {
            WriteMessage("error", error);
        }

        private static void GetLogPath()
        {
            string logp = Environment.CurrentDirectory + "/logs/";
            if (!Directory.Exists(logp))
            {
                Directory.CreateDirectory(logp);
            }
            logpath = logp + $"/{DateTime.Now.ToString("yyyy-MM-dd")}.txt";
        }

        /// <summary>
        /// 统一输出格式
        /// </summary>
        /// <param name="info"></param>
        private static void WriteMessage(string level, string msg)
        {
            try
            {
                string msglog = "[" + level + "] " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + msg + Environment.NewLine;
                //File.AppendAllText(logpath, "[" + level + "] " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + msg + Environment.NewLine);
                Console.WriteLine(msglog);
                _queuelog.Enqueue(msglog);
            }
            catch (Exception)
            {

            }

        }

        /// <summary>
        /// 大于10 M 删除
        /// </summary>
        private static void IsDeleteFile()
        {
            if (File.Exists(logpath))
            {
                //文件大小 单位 m
                long filesize = new System.IO.FileInfo(logpath).Length / 1024 / 1024;
                //大于 5M 删除文件
                if (filesize > 5)
                {
                    File.Delete(logpath);
                }
            }
        }
    }
}
